<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.params" placeholder="设备名称或编号"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="getDevices">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" icon="document" @click="handleDownload">导出设备 Excel</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" icon="document" @click="handleImport">导入设备UID Excel</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="devices" highlight-current-row v-loading="listLoading" tooltip-effect="dark" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="devName" show-overflow-tooltip label="相机名称" align="center" width="120" >
			</el-table-column>
			<el-table-column prop="guid" show-overflow-tooltip label ="设备UID" align="center" width="180" >
			</el-table-column>
			<el-table-column prop="bindUserNum" show-overflow-tooltip label="绑定用户数" align="center" width="150" >
			</el-table-column>
			<el-table-column prop="bindUserName" show-overflow-tooltip label="最后绑定用户" align="center" width="150" >
			</el-table-column>
			<el-table-column prop="bindTime" show-overflow-tooltip label="最后绑定时间" align="center" min-width="150" :formatter="formatDate" sortable>
			</el-table-column>
			<el-table-column prop="bindMobileNo" show-overflow-tooltip label="最后绑定手机" align="center" min-width="150" >
			</el-table-column>
			<el-table-column prop="isEnabled" show-overflow-tooltip label="可用" align="center" min-width="100" :formatter="formatEnabled" >
			</el-table-column>
			<el-table-column prop="creator" show-overflow-tooltip label="创建人" align="center" min-width="150" >
			</el-table-column>
			<el-table-column prop="createTime" show-overflow-tooltip label="创建时间" align="center" min-width="120" :formatter="formatDate" sortable>
			</el-table-column>
			<el-table-column prop="modifier" show-overflow-tooltip label="修改人" align="center" min-width="150" sortable>
			</el-table-column>
			<el-table-column prop="modifyTime" show-overflow-tooltip label="修改时间" align="center" min-width="120" :formatter="formatDate"  sortable>
			</el-table-column>
			<el-table-column prop="remark" show-overflow-tooltip label="备注" align="center" min-width="180">
			</el-table-column>
			<el-table-column fixed="right" label="操作" align="center" show-overflow-tooltip width="200">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button size="small" @click="handleView(scope.$index, scope.row)">预览</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="20" :total="total" style="float:right;">
			</el-pagination>
		</el-col>

		<!--编辑界面-->
		<el-dialog title="编辑" :visible.sync="editFormVisible">
			<el-form :model="editForm" label-width="100px" :rules="editFormRules" ref="editForm">
				<el-form-item label="设备UID" prop="guid">
					<el-input v-model="editForm.guid" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="相机名称" prop="devName">
					<el-input v-model="editForm.devName" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="不限制绑定" prop="devType">
					<el-switch v-model="editForm.devType"></el-switch>
				</el-form-item>
				<el-form-item label="可用" prop="isEnabled">
					<el-switch v-model="editForm.isEnabled"></el-switch>
				</el-form-item>
				<el-form-item label="备注" prop="remark">
					<el-input type="textarea" v-model="editForm.remark"></el-input>
				</el-form-item>
				<el-form-item label="绑定账号" prop="bindMobileNo">
					<el-input v-model="editForm.bindMobileNo" :disabled="true"></el-input>
				</el-form-item>
				<el-form-item label="用户名称" prop="bindUserName">
					<el-input v-model="editForm.bindUserName" :disabled="true"></el-input>
				</el-form-item>
				<el-form-item label="绑定时间" prop="bindTime">
					<el-date-picker type="date" v-model="editForm.bindTime" :disabled="true"></el-date-picker>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>

		<!--新增界面-->
		<el-dialog title="新增" :visible.sync="addFormVisible" :close-on-click-modal="false">
			<el-form :model="addForm" label-width="100px" :rules="addFormRules" ref="addForm">
				<el-form-item label="设备UID" prop="guid">
					<el-input v-model="addForm.guid" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="相机名称" prop="devName">
					<el-input v-model="addForm.devName" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="不限制绑定" prop="devType">
					<el-switch v-model="addForm.devType"></el-switch>
				</el-form-item>
				<el-form-item label="可用" prop="isEnabled">
					<el-switch v-model="addForm.isEnabled"></el-switch>
				</el-form-item>
				<el-form-item label="备注" prop="remark">
					<el-input type="textarea" v-model="addForm.remark"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="addFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>
		<!--上传组件-->
		<el-dialog title="上传" :visible.sync="uploadVisible" :close-on-click-modal="false">
			<div align="center"><el-button type="primary" @click="downloadTemp"  align="center">点击下载模板</el-button></div>
			<br>
			<div align="center">
				<el-upload drag :action="uploadUrl" :before-upload="beforeUpload" :on-success="afterSuccess"
						   :headers="headers">
					<i class="el-icon-upload"></i>
					<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
					<div class="el-upload__tip" slot="tip">只能上传xls、xlsx文件，且不超过10MB</div>
				</el-upload>
			</div>
		</el-dialog>
		<!--绑定用户列表-->
		<el-dialog title="用户绑定情况"  width="50%" :visible.sync="userListVisible" :close-on-click-modal="false">
			<el-form>
				<el-form-item>
					<el-button type="primary" v-on:click="batchUnBindUser">批量解绑</el-button>
				</el-form-item>
			</el-form>
			<el-table :data="bindUsers" v-loading="listLoading2" @selection-change="selsChange" tooltip-effect="dark" border style="width: 100%">
				<el-table-column type="selection" width="55"/>
				<el-table-column prop="devName" label="相机名称" width="150"></el-table-column>
				<el-table-column prop="guid" label="设备UID" width="150"></el-table-column>
				<el-table-column prop="bindUserName" label="绑定用户"></el-table-column>
				<el-table-column prop="bindTime" label="绑定时间" :formatter="formatDate"></el-table-column>
				<el-table-column prop="bindMobileNo" label="绑定手机"></el-table-column>
				<el-table-column label="操作" align="center" width="200">
					<template scope="scope">
						<el-button size="small" @click="handleRelease(scope.$index, scope.row)">解除绑定</el-button>
					</template>
				</el-table-column>
			</el-table>
		</el-dialog>
	</section>
</template>

<script>
    import util from '../../common/js/util'
    import {
        addDevice,
        batchRemoveDevice,
        batchUnBindUser,
        cancelBind,
        editDevice,
        exportExcelDevice,
        getBindUserList,
        getDeviceListPage,
        importExcelDeviceUrl,
        removeDevice
    } from '../../api/api'
    import {getStore} from '../../common/js/storage';

    export default {
		data() {
			return {
			    deviceId:'',//当前编辑的设备ID
			    uploadUrl:importExcelDeviceUrl(),
				filters: {
                    params: ''
				},
                headers:{
                    'accessToken':  getStore("accessToken")
				},
                devices: [],
				total: 0,
				page: 1,
				listLoading: false,
				listLoading2: false,
				sels: [],//列表选中列
				editFormVisible: false,//编辑界面是否显示
				editLoading: false,
				editFormRules: {
					guid: [
						{ required: true, message: '请输入设备编号', trigger: 'blur' },
                        { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
					],
                    devName: [
                        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
					]
				},
				//编辑界面数据
				editForm: {
					id: 0,
                    guid:'',
                    devName: '',
                    devType: true,
                    isEnabled: true,
					remark: '',
                    bindMobileNo: '',
                    bindUserName:'',
                    bindTime:''
				},
				addFormVisible: false,//新增界面是否显示
				addLoading: false,
                uploadVisible:false,
				addFormRules: {
                    guid: [
                        { required: true, message: '请输入设备编号', trigger: 'blur' },
                        { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
                    ],
                    devName: [
                        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
                    ]
				},
				//新增界面数据
				addForm: {
                    devName: '',
                    guid:'',
                    devType: true,
                    isEnabled: true,
                    remark: ''
				},
				//用户列表信息
                userListVisible:false,
                bindUsers:[]
			}
		},
		methods: {
            batchUnBindUser:function(){
                let userIds =  this.sels.map(item => item.userId).toString();
                console.log(userIds)
                if (!userIds.length>0){
                    return;
                }
                this.$confirm('确认解除绑定所选用户吗？', '提示', {}).then(() => {
                    //获取当前用户的信息
                    let para ={
                        deviceId:this.deviceId,
                        userIds:userIds
                    }
                    batchUnBindUser(para).then(data=>{
                        if (data.code == 200){
                            this.$message({
                                message: '解除成功',
                                type: 'success'
                            });
                        }
                        //重新加载绑定列表
                        this.listLoading2 = true;
                        let para = {
                            deviceId: this.deviceId,
                        }
                        //加载绑定用户列表信息
                        getBindUserList(para).then((data)=>{
                            if (data.code==200){
                                this.bindUsers = data.data;
                            }
                            this.listLoading2 = false;
                        });
                        //加载设备信息
                        this.getDevices();
                    });
                });
			},
			downloadTemp:function(){
                window.location.href='https://icecloud-test.oss-cn-beijing.aliyuncs.com/templates/UID.xls'
			},
            formatDate: function(row, column, cellValue, index){
                if (cellValue == null)
                    return '';
                return util.formatDate.formatNum(cellValue,"yyyy-MM-dd");
            },
            //是否可用转换
            formatEnabled: function (row, column) {
                return row.isEnabled ? '可用' : '不可用';
            },
            //服务器类型转换
            formatServerType: function (row, column) {
                return row.serverType == 1 ? '分派服务器' : row.serverType == 2? 'p2p服务器' : '未知';
            },

			handleCurrentChange(val) {
				this.page = val;
				this.getDevices();
			},
            afterSuccess:function(response, file, fileList){
                if (response.code == 200){
                    this.$message({
                        message: '上传成功',
                        type: 'success'
                    });
                }else {
                    this.$message({
                        message: '上传失败',
                        type: 'error'
                    });
                }
                this.uploadVisible = false;
                this.getDevices();
            },
            beforeUpload:function(file){
                let fileName=new Array()
                fileName =file.name.split('.');
                const extension = fileName[fileName.length-1] === 'xls';
                const extension2 =  fileName[fileName.length-1]=== 'xlsx';
                const isLt2M = file.size / 1024 / 1024 < 10;
                if (!extension && !extension2) {
                    this.$message({
                        message: '上传模板只能是xls、xlsx格式!',
                        type: 'warning'
                    });
                }
                if (!isLt2M) {
                    this.$message({
                        message: '上传模板大小不能超过 10MB!',
                        type: 'warning'
                    });
                }
                return extension || extension2 && isLt2M
			},
			//获取设备列表
			getDevices() {
				let para = {
					page: this.page,
                    searchKey: this.filters.params
				};
				this.listLoading = true;
				getDeviceListPage(para).then((data) => {
                    if (data.code == 200){
                        this.total = data.data.total;
                        this.devices = data.data.rows;
                        this.listLoading = false;
                    } else{
                        //跳转到错误页面
                    }
				});
                this.listLoading = false;
			},
            handleDownload:function(){
                let searchKey = this.filters.params;
                exportExcelDevice(searchKey);
            },
            handleImport:function(){
                this.uploadVisible = true;
            },
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					let para = { id: row.id };
					removeDevice(para).then((data) => {
						this.listLoading = false;
                        if (data.code == 200){
                            this.$message({
                                message: '删除成功',
                                type: 'success'
                            });
                        } else {
                            this.$message({
                                message: '删除失败',
                                type: 'error'
                            });
                        }
						this.getDevices();
                        this.listLoading = false;
                    });
				}).catch(() => {

				});
			},
            handleRelease: function(index, row){
                this.$confirm('确认解除?', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading2 = true;
                    let para = {
                        deviceId: row.devId,
						userId:row.userId
					};
                    cancelBind(para).then((data) => {
                        this.listLoading2 = false;
                        if (data.code == 200){
                            this.$message({
                                message: '解除绑定成功',
                                type: 'success'
                            });
                        } else {
                            this.$message({
                                message: '解除绑定失败',
                                type: 'error'
                            })
                        }
                        //重新加载绑定列表
                        this.listLoading2 = true;
                        let para = {
                            deviceId: row.devId,
                        }
                        //加载绑定用户列表信息
                        getBindUserList(para).then((data)=>{
                            if (data.code==200){
                                this.bindUsers = data.data;
                            }
                            this.listLoading2 = false;
                        });
                        //加载设备信息
						this.getDevices();
                    });
                }).catch(() => {

                });
			},
			//显示编辑界面
			handleEdit: function (index, row) {
				this.editFormVisible = true;
				this.editForm = Object.assign({}, row);;
			},
			//预览绑定用户
            handleView: function(index, row){
                this.userListVisible = true;
                this.listLoading2 = true;
                this.deviceId = row.id;
                let para = {
                    deviceId: row.id
				}
               	//加载绑定用户列表信息
                getBindUserList(para).then((data)=>{
                    if (data.code==200){
                        this.bindUsers = data.data;
					}
                    this.listLoading2 = false;
				});
			},
			//显示新增界面
			handleAdd: function () {
				this.addFormVisible = true;
				this.addForm = {
                    devName: '',
                    guid:'',
                    devType: true,
                    isEnabled: true,
                    remark: ''
				};
			},
			//编辑
			editSubmit: function () {
				this.$refs.editForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.editLoading = true;
							let para = Object.assign({}, this.editForm);
							editDevice(para).then((data) => {
								this.editLoading = false;
                                if (data.code == 200){
                                    this.$message({
                                        message: '提交成功',
                                        type: 'success'
                                    });
                                } else {
                                    this.$message({
                                        message: '提交失败',
                                        type: 'error'
                                    });
                                }
								this.$refs['editForm'].resetFields();
								this.editFormVisible = false;
								this.getDevices();
                                this.editLoading = false;
                            });
						});
					}
				});
			},
			//新增
			addSubmit: function () {
				this.$refs.addForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.addLoading = true;
							let para = Object.assign({}, this.addForm);
							addDevice(para).then((data) => {
								this.addLoading = false;
                                if (data.code == 200){
                                    this.$message({
                                        message: '提交成功',
                                        type: 'success'
                                    });
                                } else {
                                    this.$message({
                                        message: '提交失败',
                                        type: 'error'
                                    });
                                }
								this.$refs['addForm'].resetFields();
								this.addFormVisible = false;
								this.getDevices();
							});
                            this.addLoading = false;
						});
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id).toString();
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					let para = { ids: ids };
					batchRemoveDevice(para).then((data) => {
						this.listLoading = false;
                        if (data.code == 200){
                            this.$message({
                                message: '删除成功',
                                type: 'success'
                            });
                        } else {
                            this.$message({
                                message: '删除失败',
                                type: 'error'
                            });
                        }
						this.getDevices();
                        this.listLoading = false;
					});
				}).catch(() => {

				});
			}
		},
		mounted() {
			this.getDevices();
		}
	}
</script>

